package com.hao.project.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hao.project.model.entity.User;
import com.hao.project.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author haoge
 * @version 1.0
 * @date 2023/5/17 19:22
 * <p>
 * 预热缓存任务
 */

@Component
@Slf4j
public class PreCacheJob {
    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    private List<Long> mainUserList = Arrays.asList(4L);

    //每天执行
    //加载推荐用户
    @Scheduled (cron = "0 46 19 * * ?  ")
    public void doCacheRecommendUser() {
        RLock lock = redissonClient.getLock("haoge:precachejob:docache:lock");
        try {
            //只有一个线程能获取锁
            if (lock.tryLock(0L,-1, TimeUnit.MILLISECONDS)) {
                //只缓存活跃用户
                for (Long userId : mainUserList) {
                    User user = userService.getById(userId);
                    String redisKey = String.format("haoge:user:recommend:%s", userId);
                    List<User> userList = userService.matchUsers(20, user);
                    //写缓存
                    try {
                        redisTemplate.opsForValue().set(redisKey, userList, 100000, TimeUnit.SECONDS);
                    } catch (Exception e) {
                        log.error("redis set value error", e);
                    }
                }
            }
        } catch (InterruptedException e) {
            log.error("redis set value error",e);
        }finally {
            //只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }

    }
}
